package com.mybatis.jpa.statement.builder;

import java.lang.reflect.Method;

import com.mybatis.jpa.meta.MybatisColumnMeta;
import com.mybatis.jpa.statement.SqlAssistant;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.SqlCommandType;

import com.mybatis.jpa.meta.PersistentMeta;
import com.mybatis.jpa.statement.MybatisStatementAdapter;

/**
 * 批量更新
 * @author wanglei
 * @date 2020 -02-06 11:06:32
 */
public class BatchUpdateBuilder implements StatementBuildable {

	@Override
	public String buildSQL(PersistentMeta persistentMeta, Method method) {
		// columns
		StringBuilder sets = new StringBuilder();
		sets.append("<trim prefix='' suffix='' suffixOverrides=',' > ");
		String alias = "entity.";
		for (MybatisColumnMeta columnMeta : persistentMeta.getColumnMetaMap().values()) {
			if (persistentMeta.getPrimaryColumnMeta().getProperty().equals(columnMeta.getProperty())) {
				continue;
			}
			if (columnMeta.isVersion()) {
				sets.append(columnMeta.getColumnName()).append(" = ").append( columnMeta.getColumnName() + " + 1")
						.append(" , ");
				continue;
			}
			if(!isIncludeNull()){
				sets.append("<if test='" + alias + columnMeta.getProperty() + "!= null'> ");
			}

			// columnName = #{ }
			sets.append(columnMeta.getColumnName()).append(" = ").append(SqlAssistant.resolveSqlParameter(columnMeta, "entity"))
					.append(" , ");
			if(!isIncludeNull()){
				sets.append("</if> ");
			}
		}

		sets.append("</trim> ");
		String reuslt =  "<script><foreach collection=\"list\" item=\"entity\" index=\"index\" open=\"\" close=\"\" separator=\";\">" + "UPDATE " + persistentMeta.getTableNameFlag() + " set " + sets.toString()
				+ SqlAssistant.buildSingleCondition(method, persistentMeta,"entity") + "</foreach></script>";
		return reuslt;
	}

	@Override
	public void parseStatement(MybatisStatementAdapter adapter, PersistentMeta persistentMeta, Method method) {
		// 方法名
		adapter.setMethodName(method.getName());
		// 参数类型 
		adapter.setParameterTypeClass(persistentMeta.getType());
		// sqlScript
		adapter.setSqlScript(buildSQL(persistentMeta, method));
		// 返回值类型
		adapter.setResultType(int.class);
		adapter.setResultMapId(null);

		adapter.setSqlCommandType(SqlCommandType.UPDATE);

		// 主键策略
		adapter.setKeyGenerator(new NoKeyGenerator());
		adapter.setKeyProperty(null);
		adapter.setKeyColumn(null);

		adapter.parseStatement();

	}

	public boolean isIncludeNull(){
		return false;
	}
}
